package com.leo.biz.service.zookeeper;

import com.leo.biz.service.pub.TypeUtils;
import com.leo.biz.service.rediszkagent.RedisZkAgent;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
/**
 * Created by leo on 2016/10/10.
 */
@Service
public class ZkTest {

    static Logger logger = org.slf4j.LoggerFactory.getLogger(ZkTest.class);

    public static final String REDIS_ROOT_CFG = "/redis-cfg";

    /*为了让redisZkAgent先于ZkTest初始化*/
    @Autowired
    public RedisZkAgent redisZkAgent;

    public static Map<String,String> getRedisConfigFromZK() throws Exception {
        Map<String,String>ret=null;
        // 创建一个与服务器的连接
        ZooKeeper zk = new ZooKeeper("localhost:2181", 30000, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {
                logger.info("新事件触发:" + event.getState() + ":" + event.getType().name() + ":" + event.getWrapper() + ":" + event.getPath());
            }
        });
        if(zk.exists(REDIS_ROOT_CFG, true) == null)
        {
            logger.info("No Found "+REDIS_ROOT_CFG+" from zookeeper ");
        }else
        {
            List<String> children = zk.getChildren(REDIS_ROOT_CFG, true);
            for (int i=0;i<children.size();i++)
            {
                logger.info(children.get(i).toString());
                byte[] temp=zk.getData(REDIS_ROOT_CFG+"/"+children.get(i).toString(),null,null);
                logger.info(TypeUtils.byte2String(temp, "UTF-8"));
                ret= TypeUtils.json2Map(TypeUtils.byte2String(temp, "UTF-8"));
            }
            logger.info(children.size() + "");
        }
        zk.close();
        return ret;
    }

    // 根节点
    public static final String ROOT = "/app-list";
    public static void test() throws Exception {
        // 创建一个与服务器的连接
        ZooKeeper zk = new ZooKeeper("localhost:2181", 30000, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {
                logger.info("状态:" + event.getState() + ":" + event.getType() + ":" + event.getWrapper() + ":" + event.getPath());
            }
        });
        if(zk.exists(ROOT, true) == null)
        {
            // 创建一个总的目录ktv，并不控制权限，这里需要用持久化节点，不然下面的节点创建容易出错
            zk.create(ROOT, ROOT.getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        if(zk.exists(ROOT+"/appB", true)==null)
        {

            zk.create(ROOT+"/appB", "appB".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }

        if(zk.exists(ROOT, true) != null)
        {
            List<String> ktvs = zk.getChildren(ROOT, true);
            logger.info(ktvs.size() + "");

        }
        // 根目录得最后删除的

        zk.close();
    }
}
